<template>
  <div v-loading="loading">
    <el-form ref="ruleFormRef" :inline="true" :rules="rules" :model="form" label-width="140px">
      <el-form-item label="当前订单状态:" prop="orderStatus">
        <el-select disabled v-model="form.orderStatus" placeholder="请选择订单状态">
          <el-option v-for="item in orderstatus" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>

      <div v-if="showNextStatus">
        <el-form-item label="下一步订单状态:" prop="nextorderStatus">
          <el-select disabled v-model="form.nextorderStatus" placeholder="请选择订单状态">
            <el-option v-for="item in orderstatus" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>
      </div>
      <div v-if="form.orderStatus === '意向订单'">
        <el-form-item label="已缴订金金额:" prop="money">
          <el-input v-model="form.money" />
        </el-form-item>
      </div>
      <div v-else-if="form.orderStatus === '设计师回图'">
        <el-form-item label="量尺时间:" prop="measuringTime">
          <el-input v-model="form.measuringTime" disabled />
        </el-form-item>
      </div>
      <div v-else-if="form.orderStatus === '订金订单'">
        <el-form-item label="设计部门:" prop="officeCode">
          <el-select v-model="form.officeCode" placeholder="请选择设计部门">
            <el-option v-for="item in officeCode.data" :key="item.officeCode" :label="item.officeName" :value="item.officeCode" />
          </el-select>
        </el-form-item>
      </div>
      <div v-else-if="form.orderStatus === '派单量尺'">
        <el-form-item label="设计师:" prop="designer">
          <el-select v-model="form.designer" placeholder="请选择设计师">
            <el-option v-for="item in designer.data" :key="item.empCode" :label="item.empName" :value="item.empCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择量尺时间:" prop="measuringTime">
          <el-date-picker v-model="form.measuringTime" type="date" placeholder="请选择量尺时间" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
        </el-form-item>
      </div>
      <div v-else-if="form.orderStatus === '设计师回图'"></div>
      <div v-else-if="form.orderStatus === '合同确图'"></div>
      <div v-else-if="form.orderStatus === '下单审单'"></div>
      <div v-else-if="form.orderStatus === '下单分单'">
        <el-form-item label="柜体工厂" prop="executor">
          <el-select v-model="form.executor" placeholder="请选择代工厂">
            <el-option v-for="item in factoryData" :key="item.empCode" :label="item.empName" :value="item.empCode" />
          </el-select>
        </el-form-item>

        <!--       <el-form-item label="确认供应商" prop="orderManager" v-show="count==0">-->
        <!--         <el-button type="primary" @click="getChecked" style="margin-top: 2%;margin:0 auto;">确认供应商</el-button>-->
        <!--       </el-form-item>-->
        <!--       <el-form-item label="供应商备注:" prop="orderManager">-->
        <!--       </el-form-item>-->
        <!--       <el-form-item label="代工厂备注" style="margin-top: 2%">-->
        <!--         <el-input v-model="form.comment" type="textarea"  placeholder="请输入代工厂备注" style="width: 400px" />-->
        <!--       </el-form-item>-->
        <el-form-item label="供应商:" prop="orderManager">
          <el-checkbox v-model="item.checked" :label="item.empName" border v-for="(item, index) in allSupplier" :key="item" style="margin-top: 1%" :disabled="count > 0" />
        </el-form-item>
      </div>
      <div v-else-if="form.orderStatus === '采购'"></div>
      <div v-else-if="form.orderStatus === '物流配送'"></div>
      <div v-else-if="form.orderStatus === '安装派单'">
        <el-form-item label="请选择安装师傅:" prop="executor">
          <el-select v-model="form.executor" placeholder="请选择安装师傅">
            <el-option v-for="item in Inames.data" :label="item.name" :value="item.ID" :key="item.ID" />
          </el-select>
        </el-form-item>
      </div>
      <!-- <div v-else-if="form.orderStatus === '安装派单'">
        <el-form-item label="选择安装师傅派单:">
          <el-select v-model="form.executor" placeholder="选择安装师傅派单">
            <el-option v-for="s in Inames.data" :label="s.name" :value="s.name" :key="s.code" />
          </el-select>
        </el-form-item>
      </div> -->
      <div v-else-if="form.orderStatus === '交付安装'"></div>
      <div v-else-if="form.orderStatus === '交付验收'">
        <el-form-item label="是否有售后:" prop="afterSales">
          <el-select v-model="form.afterSales" placeholder="请选择是否有售后">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
      </div>
      <div v-else-if="form.orderStatus === '客服回访'"></div>
      <div v-else>
        <!-- <el-form-item label="执行人:">
          <el-tree-select
            v-model="form.executor"
            :data="data"
            :render-after-expand="false"
            placeholder="请选择设计主管"
          />
        </el-form-item> -->
      </div>
      <div v-if="form.orderStatus != '结束'">
        <el-form-item label="上传图片:">
          <el-upload
            v-if="Env == 'development'"
            v-model:file-list="fileList"
            :action="'http://localhost:3100/js/a/product/file/upload?orderId=' + props.orderid + '&orderStatus=' + status_id"
            list-type="picture-card"
            :on-success="uploadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-upload v-else v-model:file-list="fileList" :action="'http://' + GlobUrl + '/js/a/product/file/upload?orderId=' + props.orderid + '&orderStatus=' + status_id" list-type="picture-card" :on-success="uploadSuccess" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" multiple>
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="form.comment" type="textarea" style="width: 400px" />
        </el-form-item>
      </div>
    </el-form>
    <!--  必须有下一状态时，才能进行确认操作-->
    <div class="_button" v-show="showNextStatus">
      <el-button type="primary" size="large" @click="onSubmit(ruleFormRef)" v-if="form.orderStatus != '分单'">{{ form.orderStatus === '合同确图' || form.orderStatus === '下单审单' ? '同意' : '确认' }}</el-button>
      <el-button type="danger" size="large" @click="rejectHTQT(ruleFormRef)" v-if="form.orderStatus === '合同确图' || form.orderStatus === '下单审单'">拒绝</el-button>
      <!-- <el-button
        type="primary"
        size="large"
        @click="showQuery()"
        v-if="form.orderStatus === '物流配送'"
        >查看信息</el-button
      > -->
    </div>
    <!-- <ShowMessage ref="showMessageRef" /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, watch, defineEmits } from 'vue'
import { OrderListData, tbgetDesigner, tbgetOfficeCode } from '/@/api/tb/tbOrder'
import {
  tbAddNext,
  tbsplitOrder,
  tbYXtoDJ,
  tbDJtoPD,
  tbPDtoSJSHT,
  tbSJSHTtoHTQT,
  tbSJSHTtoXDSD,
  tbXDSDtoFD,
  tbSJSHTrejectXDSD,
  tbXDSDrejectFD,
  tbPurchaseToProduction,
  tbshowInstaller,
  tbdeliveryToInstallSending,
  tbsendingToInstalling,
  tbinstallingToCheck,
  tbcheckToEnding
} from '/@/api/tb/tbaddNext'
import { tbDictList } from '/@/api/tb/tbDictType'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { GetWhole } from '../Util_Function/getOrderWhole'
import { tbFindAllSupplier } from '/@/api/tb/tbSupplierOrder'
import { getEnv } from '/@/utils/env'
import { GlobUrl } from '../Util_Function/uploadPicture'
// import ShowMessage from '../tbMyOrder/components/ShowMessage.vue'
// import { tbGetnames } from '/@/api/tb/tbOrderStatus'
const Env = getEnv()
const orderstatus = ref([])
const officeCode = ref([])
let Inames = ref()
const props = defineProps({
  orderid: String
})
const showMessageRef = ref()
const designer = ref([])
let status_id = reactive('')
const emit = defineEmits(['editForm'])
const ruleFormRef = ref<any>()
const form = reactive({
  orderId: '', // 订单号
  executor: '', //订单管理员
  orderStatus: '', // 订单状态
  nextorderStatus: '', //下一步订单状态
  reserveAmount: '', // 定金金额
  comment: '', // 备注
  designer: '', // 设计师
  officeCode: '', // 设计部门
  estimatedAmount: '', //预估金额
  fileList: '',
  money: '',
  measuringTime: '', //量尺时间
  afterSales: '', //是否有售后
  // supplierInfo:''
})
const fileList = ref<UploadUserFile[]>()
const showNextStatus = ref<any>(true)
const data = ref([])
const loading = ref(true)
watch(
  () => props.orderid, //这样才可以检测到对象里面的值
  async () => {
    loading.value = true
    fileList.value = []
    designer.value = await tbgetDesigner()
    officeCode.value = await tbgetOfficeCode()
    const res = await OrderListData({ orderId: props.orderid })
    // console.log(res);
    const findAllSupplier = async () => {
  const res = await tbFindAllSupplier()
  allSupplier.value = res.data.supplier
  factoryData.value = res.data.factory
}
findAllSupplier()
    if (res.list) {
      status_id = res.list[0]?.orderStatus
      for (let key in form) {
        form[key] = ''
        if (key != 'afterSales' && key != 'comment') {
          form[key] = res.list[0][key]
        }
      }
    }
    if (form.orderStatus === '派单量尺') {
      form.measuringTime = new Date()

      function msToDate(msec) {
        let datetime = new Date(msec)
        let year = datetime.getFullYear()
        let month = datetime.getMonth()
        let date = datetime.getDate()
        let result2 = year + '-' + (month + 1 >= 10 ? month + 1 : '0' + (month + 1)) + '-' + (date + 1 < 10 ? '0' + date : date)
        return result2
      }
      form.measuringTime = msToDate(form.measuringTime).withoutTime
    }
    getOffices()
  },
  { immediate: true }
)
const getOffices = async () => {
  const status = await tbDictList({ dict: 'the_order_status' })
  orderstatus.value = status.data
  for (let index = 0; index < status.data.length; index++) {
    if (form.orderStatus == status.data[index].dictLabel) {
      if (index === status.data.length - 1) {
        showNextStatus.value = false
      } else {
        showNextStatus.value = true
        form.nextorderStatus = parseInt(status.data[index + 1].dictValue) + ''
      }
    }
  }
  form.orderId = props.orderid
  data.value = await GetWhole()
  if (data.value.length && orderstatus.value.length) {
    loading.value = false
  }
}
const rules = reactive({
  orderStatus: [{ required: true, message: '请选择订单状态', trigger: 'change' }],
  nextorderStatus: [{ required: true, message: '请选择订单状态', trigger: 'change' }],
  money: [{ required: true, message: '请输入已缴定金金额', trigger: 'blur' }],
  officeCode: [{ required: true, message: '设计部门为必填项', trigger: 'change' }],
  estimatedAmount: [{ required: true, message: '请输入预估金额', trigger: 'blur' }],
  designer: [{ required: true, message: '请选择设计师', trigger: 'change' }],
  executor: [{ required: true, message: '请选择执行人', trigger: 'change' }],
  measuringTime: [{ required: true, message: '请选择量尺时间', trigger: 'change' }],
  afterSales: [{ required: true, message: '请选择是否有售后', trigger: 'change' }]
})
// const showQuery = () => {
//   showMessageRef.value.open();
// };
const onSubmit = async formEl => {
  if (!formEl) return
  await formEl.validate(async valid => {
    if (valid) {
      const res = ref()
      if (form.orderStatus == '意向订单') {
        res.value = await tbYXtoDJ(form)
      } else if (form.orderStatus == '订金订单') {
        res.value = await tbDJtoPD(form)
      } else if (form.orderStatus == '派单量尺') {
        res.value = await tbPDtoSJSHT(form)
      } else if (form.orderStatus == '设计师回图') {
        res.value = await tbSJSHTtoHTQT(form)
      } else if (form.orderStatus == '合同确图') {
        res.value = await tbSJSHTtoXDSD(form)
      } else if (form.orderStatus == '下单审单') {
        res.value = await tbXDSDtoFD(form)
      } else if (form.orderStatus == '下单分单') {
        for (let i = 0; i < allSupplier.value.length; i++) {
          if (allSupplier.value[i].checked) {
            checkedSupplier.value.push(allSupplier.value[i].empName)
          }
        }
        form.supplierInfo = checkedSupplier.value + ''
          res.value = await tbsplitOrder(form)
      } else if (form.orderStatus == '采购') {
        res.value = await tbPurchaseToProduction(form)
      } else if (form.orderStatus === '物流配送') {
        res.value = await tbdeliveryToInstallSending(form)
      } else if (form.orderStatus === '安装派单') {
        res.value = await tbsendingToInstalling(form)
      } else if (form.orderStatus === '交付安装') {
        res.value = await tbinstallingToCheck(form)
      } else if (form.orderStatus === '交付验收' || form.orderStatus === '客服回访') {
        res.value = await tbcheckToEnding(form)
      }
      // else {
      //   res.value = await tbAddNext(form);
      // }
      closedialog(JSON.parse(JSON.stringify(res.value)))
    }
  })
}
const closedialog = res => {
  if (res.result) {
    for (let key in form) {
      form[key] = ''
    }
    allSupplier.value=[
  {
    empName: '获取数据',
    empCode: 'test'
  }
]
    // for(let i in allSupplier){
    //   allSupplier[i].checked=false
    // }
    emit('editForm')
    ElMessage({
      message: res.message,
      type: 'success'
    })
  } else {
    ElMessage.error(res.message)
  }
}

const rejectHTQT = async formEl => {
  if (!formEl) return
  if (form.orderStatus == '下单审单') {
    await formEl.validate(async valid => {
      if (valid) {
        let res = await tbXDSDrejectFD(form)
        closedialog(res)
      }
    })
  } else if (form.orderStatus == '合同确图') {
    await formEl.validate(async valid => {
      if (valid) {
        let res = await tbSJSHTrejectXDSD(form)
        closedialog(res)
      }
    })
  }
}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
let url = reactive('')
const pushFile = () => {
  url = ''
  for (let i = 0; i < JSON.parse(JSON.stringify(fileList))._value.length; i++) {
    if (i == JSON.parse(JSON.stringify(fileList))._value.length - 1) {
      url = url + JSON.parse(JSON.stringify(fileList))._value[i].response.data.url
    } else {
      url = url + JSON.parse(JSON.stringify(fileList))._value[i].response.data.url + ','
    }
  }
  form.fileList = url
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  pushFile()
}

//获取到所有的供应商
const allSupplier = ref([
  {
    empName: '获取数据',
    empCode: 'test'
  }
])

//选择的供应商
let checkedSupplier = ref([])

//柜体
const factoryData = ref([])

let count = ref(0)
let suppliers = []
let comments = []

const getChecked = () => {
  //构建已经选择的内容
  for (let i = 0; i < allSupplier.value.length; i++) {
    if (allSupplier[i].checked) {
      checkedSupplier.value.push(allSupplier[i])
    }
  }
}

const sendData = async formEl => {
  //构造相关参数
  // let empCodes = [];
  // let comments = []
  // for (let i = 0; i < checkedSupplier.value.length; i++) {
  //   empCodes.push(checkedSupplier.value[i].empCode)
  //   comments.push(checkedSupplier.value[i].comment)
  // }
  // form.comments = comments.toString()
  // form.empCodes = empCodes.toString()
  //
  // if (form.empCodes==""||form.empCodes.length==0){
  //   ElMessage.warning("请至少选择一个供应商")
  // }else {
  //   // 发送请求
  //   await onSubmit(formEl)
  // }
}
const uploadSuccess = (res, file, files) => {
  if (res.code != 200) {
    ElMessage.error('上传失败')
  } else {
    pushFile()
  }
}

const handlePictureCardPreview: UploadProps['onPreview'] = uploadFile => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const getName = async () => {
  Inames.value = await tbshowInstaller()
  // console.log(Inames);
}

getName()
</script>

<style lang="less" scoped>
._button {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding-right: 50px;
}
</style>
